<template>
  <div
    :class="animate"
    :style="{ height: height, width: width }"
    :id="chartOption.bindingDiv"
    ref="chartDiv"
  />
</template>

<script>
import echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import resize from "@/views/dashboard/mixins/resize";

import "../../animate/animate.css";

import { parseQueryString, fIsUrL } from "../../util/urlUtil";
import { chartApiBar, remoteChartApi,chartBIanalysis } from "@/api/tool/datav/chartApi";
import { linkChart } from "../../util/LinkageChart";
import { addOption } from "../../codegen/codegen";
import { getFormsource } from "@/api/tool/datav/formsource";
import { barTimeBIanalysis } from "@/api/tool/datav/chartBI/chartBarTimeBI";
import VueEvent from "@/views/tool/datav/VueEvent";
import { websocketCommand } from "../../util/websocket.js";
import { dealWithData,testData } from "../../util/utilFun.js";
const animationDuration = 6000;

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart"
    },
    width: {
      type: String,
      default: "100%"
    },
    height: {
      type: String,
      default: "100%"
    },
    chartOption: {
      type: Object
    },
    drawingList: {
      type: Array
    }
  },
  data() {
    return {
      chart: null,
      //dataOption: this.chartOption,
      timer: "",
      wsObj: null,
      wsFlag: false,
      wsTimer: "",
      wsValue: null,
      animate: this.className
    };
  },
  watch: {
    width() {
      this.$nextTick(() => {
        this.chart.resize();
      });
    },
    height() {
      this.$nextTick(() => {
        this.chart.resize();
      });
    },
    chartOption: {
      deep: true,
      handler(newVal) {
        this.$nextTick(() => {
          this.setOptions(JSON.parse(JSON.stringify(newVal)));
        });
      }
    },
    "chartOption.theme": {
      handler() {
        if (this.chart != null) {
          this.chart.dispose();
          this.chart = null;
          this.initChart();
        }
      }
    },
    "chartOption.timeout": {
      handler() {
        this.chart.dispose();
        this.chart = null;
        this.initChart();
      }
    },
    "chartOption.dataSourceType": {
      handler(value) {
        //切换数据源重新连接
        if (value !== "websocket") {
          this.wsFlag = false;
          //每次切换数据源恢复原来动画
          this.animate = this.className;
        }
        if (value !== "url") {
          clearTimeout(this.timer);
        } 
      }
    },
    "chartOption.interfaceKey": {
      handler(newValue, oldValue) {
        //初始化不创建连接，改变接口地址重新创建
        if (oldValue !== undefined && oldValue != "") {
          this.wsValue = null;
          this.closeWs();
          this.createWs();
          this.animate = this.className;
        }
      }
    },
    wsFlag: {
      handler(value) {
        if (!value) {
          this.wsValue = null;
          this.closeWs();
        }
      }
    },
    className: {
      handler(value) {
        this.animate = value;
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
    clearTimeout(this.timer);
    if (this.wsFlag) {
      this.closeWs();
    }
  },
  methods: {
    initChart() {
      echarts.registerTheme("customTheme", this.chartOption.theme);
      this.chart = echarts.init(this.$el, "customTheme");
      this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
      //判断是否开启定时器，当是访问url接口时候并且timeout不为0时候开启定时器
      if (this.timer != "") {
        clearTimeout(this.timer);
      }
      if (
        (this.chartOption.dataSourceType == 'url' || this.chartOption.dataSourceType == 'database') &&
        this.chartOption.timeout > 0
      ) {
        let timerTask = () => {
          this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
          this.timer = setTimeout(() => {
            timerTask();
          }, this.chartOption.timeout);
        };

        timerTask();
      }else{
        this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
      }
    },
    setOptions: async function(dataOption) {
      //初始化数据
      //如果不是静态数据就调用接口给staticDataValue赋值
      if (dataOption.dataSourceType == "url") {
        let paramJson = parseQueryString(dataOption.requestParameters);

        let interfaceURL = dataOption.interfaceURL;
        dataOption.staticDataValue = await chartApiBar(
          dataOption.requestMethod,
          interfaceURL,
          paramJson,
          dataOption.token
        );
      } else if (dataOption.dataSourceType == "database") {
        if (
          dataOption.database.executeSql != undefined &&
          dataOption.database.executeSql != ""
        ) {
          let result = [];
          if(dataOption.database.sqlType != 'custom'){
          
            result = await barTimeBIanalysis(dataOption.database);
          }else{
            result = await chartBIanalysis(dataOption.database);
          }
          if (result.code == 200) {
            dataOption.staticDataValue = result.data;
            //console.log(dataOption.staticDataValue);
          } else {
            alert("操作数据库错误");
          }
        }
      } else if (dataOption.dataSourceType == "form") {
        if (dataOption.formSource != undefined) {
          let response = await getFormsource(dataOption.formSource.id);
          dataOption.staticDataValue = JSON.parse(response.data.formData);
        }
      } else if (dataOption.dataSourceType == "websocket") {
        if (
          dataOption.interfaceKey != undefined &&
          dataOption.interfaceKey != ""
        ) {
          if (!this.wsFlag) {
            this.wsFlag = true;
            this.wsValue = null;
            this.createWs();
          }
          if (this.wsValue != null) {
            dataOption.staticDataValue = this.wsValue;
          }
        }
      }

     
      //数据格式转换
      if(dataOption.newDataFormat == true && !(dataOption.dataSourceType == 'database' && dataOption.bi != null)){
         
        let sortData = dealWithData(dataOption.staticDataValue,"series")
        let staticValue = [];
        sortData.forEach(element => {
          let res = {"name":element.type};
          let seriesData = dealWithData(element.data,"type")
          for(let i=0;i<seriesData.length;i++){
            let data = [];
            let label = [];
            seriesData[i].data.forEach(ele => {
                label.push(ele.name);
                data.push(ele.value);
              });
            if(i==0){
              let data1 = {"name":seriesData[i].type,"data":data};
              res.label = label;
              res.data1 = data1;
           
            }else{
              let data2 = {"name":seriesData[i].type,"data":data};
              res.data2 = data2;
            }
          }
          staticValue.push(res)
        });
        dataOption.staticDataValue = staticValue;
      }

      var data = dataOption.staticDataValue;
      var myData = data[0].label;
      var data1 = {};
      var data2 = {};
      var timeLineData = [];
      for (var i = 0; i < data.length; i++) {
        data1[data[i].name] = data[i].data1.data;
        data2[data[i].name] = data[i].data2.data;
        timeLineData.push(data[i].name);
      }
      //应用主题
      if (dataOption.isThemeColor == true) {
        var color = this.chartOption.theme.color;

        dataOption.leftColor = color[0 % color.length];
        dataOption.rightColor = color[2 % color.length];
        dataOption.leftfocusColor = color[1 % color.length];
        dataOption.rightfocusColor = color[3 % color.length];
      }

      var option = {
        baseOption: {
          timeline: {
            //时间轴
            show: true,
            axisType: "category",
            tooltip: {
              show: true,
              formatter: function(params) {
                return dataOption.timetooltip.replace("?", params.name); //时间轴提示文字
              }
            },
            autoPlay: dataOption.isautoplay == false ? false : true, //自动播放
            currentIndex: 0, //默认数据
            playInterval: dataOption.playinterval, //播放速度
            label: {
              normal: {
                show: true,
                interval: "auto", //下标的显示间隔
                formatter: "{value}" + dataOption.suffix //下标值
              }
            },
            data: []
          },
          title: {
            show: dataOption.istitle == false ? false : true,
            //   text:'大北京景点帅哥美女统计',
            textStyle: {
              color: "#fff",
              fontSize: 16
            },
            subtext: dataOption.subtitle
          },
          legend: {
            //图例
            data: [data[0].data1.name, data[0].data2.name],
            top: 4,
            right: "20%",
            textStyle: {
              color: "#fff"
            }
          },
          tooltip: {
            //提示
            show: true,
            trigger: "axis",
            formatter: "{b}<br/>{a}: {c}" + dataOption.datasuffix,
            axisPointer: {
              type: "shadow"
            }
          },

          grid: [
            {
              //左柱
              show: false,
              left: "4%",
              top: 60,
              bottom: 60,
              containLabel: true,
              width: "37%"
            },
            {
              //中间坐标
              show: false,
              left: "50.5%",
              top: 80,
              bottom: 60,
              width: "0%"
            },
            {
              //右柱
              show: false,
              right: "4%",
              top: 60,
              bottom: 60,
              containLabel: true,
              width: "37%"
            }
          ],

          xAxis: [
            {
              type: "value",
              inverse: true,
              axisLine: {
                show: false
              },
              axisTick: {
                show: false
              },
              position: "top",
              axisLabel: {
                show: true,
                textStyle: {
                  color: "#fff",
                  fontSize: 12
                }
              },
              splitLine: {
                show: true,
                lineStyle: {
                  color: "#1F2022",
                  width: 1,
                  type: "solid"
                }
              }
            },
            {
              gridIndex: 1,
              show: false
            },
            {
              gridIndex: 2,
              type: "value",
              axisLine: {
                show: false
              },
              axisTick: {
                show: false
              },
              position: "top",
              axisLabel: {
                show: true,
                textStyle: {
                  color: "#fff",
                  fontSize: 12
                }
              },
              splitLine: {
                show: true,
                lineStyle: {
                  color: "#1F2022",
                  width: 1,
                  type: "solid"
                }
              }
            }
          ],
          yAxis: [
            {
              type: "category",
              inverse: true,
              position: "right",
              axisLine: {
                show: false
              },
              axisTick: {
                show: false
              },
              axisLabel: {
                show: false,
                margin: 8,
                textStyle: {
                  color: "#fff",
                  fontSize: 12
                }
              },
              data: myData
            },
            {
              gridIndex: 1,
              type: "category",
              inverse: true,
              position: "left",
              axisLine: {
                show: false
              },
              axisTick: {
                show: false
              },
              axisLabel: {
                show: true,
                textStyle: {
                  color: "#fff",
                  fontSize: 12
                }
              },
              data: myData.map(function(value) {
                return {
                  value: value,
                  textStyle: {
                    align: "center"
                  }
                };
              })
            },
            {
              gridIndex: 2,
              type: "category",
              inverse: true,
              position: "left",
              axisLine: {
                show: false
              },
              axisTick: {
                show: false
              },
              axisLabel: {
                show: false,
                textStyle: {
                  color: "#fff",
                  fontSize: 12
                }
              },
              data: myData
            }
          ],
          series: []
        },

        options: []
      };

      for (var i = 0; i < timeLineData.length; i++) {
        option.baseOption.timeline.data.push(timeLineData[i]);
        option.options.push({
          title: {
            text: dataOption.title.replace("?", timeLineData[i])
          },
          series: [
            {
              name: data[0].data1.name,
              type: "bar",
              barWidth: dataOption.barwidth,
              label: {
                normal: {
                  show: false
                },
                emphasis: {
                  show: true,
                  position: "left",
                  offset: [0, 0],
                  textStyle: {
                    color: "#fff",
                    fontSize: 14
                  }
                }
              },
              itemStyle: {
                normal: {
                  color: dataOption.leftColor
                },
                emphasis: {
                  color: dataOption.leftfocusColor
                }
              },
              data: data1[timeLineData[i]]
            },
            {
              name: data[0].data2.name,
              type: "bar",
              barGap: 20,
              barWidth: dataOption.barwidth,
              xAxisIndex: 2,
              yAxisIndex: 2,
              label: {
                normal: {
                  show: false
                },
                emphasis: {
                  show: true,
                  position: "right",
                  offset: [0, 0],
                  textStyle: {
                    color: "#fff",
                    fontSize: 14
                  }
                }
              },
              itemStyle: {
                normal: {
                  color: dataOption.rightColor
                },
                emphasis: {
                  color: dataOption.rightfocusColor
                }
              },
              data: data2[timeLineData[i]]
            }
          ]
        });
      }
      //执行通用处理函数
      if(dataOption.customData != undefined && dataOption.customData != ""){
        try {
          option = (
          
            //里面为要处理的代码块
          eval(dataOption.customData) 
          
          )(
            option,
            dataOption.staticDataValue,
            this.$refs.chartDiv
          );
        } catch (error) {
          console.log(error)
        }
       }
        //交互组件配置
      if(dataOption.interactData != undefined && dataOption.interactData != ""){
          try {
              option = (        
              //里面为要处理的代码块
              eval(dataOption.interactData)             
            )(
            option,
            dataOption.staticDataValue,
            this.$refs.chartDiv
            );
          } catch (error) {
            console.log(error)
          }               
       }     
      this.chart.setOption(option, true);

      addOption(dataOption.bindingDiv, option);

      //开启图表联动
      if (dataOption.isLink == true) {
        this.chart.off("click");
        this.chart.on("click", params => {
          //设置参数
          let arrObject = {
            legendName: params.seriesName,
            seriesName: params.name,
            data: params.value
          };

          let arrs = JSON.stringify(arrObject);

          //获取绑定的图表
          let bindList = this.chartOption.bindList;

          if (bindList.length > 0) {
            linkChart(dataOption.arrName, arrs, bindList, this.drawingList);
          }
        });
      }
      //开启图表下钻
      else if (dataOption.isDrillDown == true) {
        this.chart.off("click");
        this.chart.on("click", params => {
          //设置参数
          let arrObject = {
            legendName: params.seriesName,
            seriesName: params.name,
            data: params.value
          };

          let arrs = JSON.stringify(arrObject);

          //获取绑定的图表
          let drillDownChartOption = this.chartOption.drillDownChartOption;

          if (
            drillDownChartOption != undefined &&
            drillDownChartOption != null
          ) {
            this.$set(
              this.chartOption.drillDownChartOption.chartOption,
              "requestParameters",
              "drillParam=" + arrs
            );
            //发送下钻消息
            VueEvent.$emit(
              "drill_down_msg",
              this.chartOption.drillDownChartOption
            );
          }
        });
      } else {
        //关闭图表联动，取消echart点击事件
        this.chart.off("click");
      }

      //开启远程图表控制
      if (dataOption.isRemote == true) {
        if (dataOption.remote != undefined && dataOption.remote != null) {
          this.chart.off("click");
          this.chart.on("click", params => {
            //设置参数
            let arrObject = {
              legendName: params.name,
              seriesName: params.seriesName,
              data: params.value
            };

            let remoteData = { ...dataOption.remote };
            remoteData.query = arrObject;
            //调用接口
            remoteChartApi(remoteData);
          });
        }
      }
    },
    //  ws连接成功，后台返回的ws数据
    receiveMsg(e) {
      if (e.action == "chat") {
        // console.log('服务端推送',e);
        this.wsValue = JSON.parse(e.result);
        this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
      }
    },
    // 建立连接、发起ws请求，以心跳方式，向服务端发送数据
    createWs() {
      this.wsObj = new WebSocket(process.env.VUE_APP_WEBSOCKET);
      // 若为对象类型，以回调方式发送
      websocketCommand(
        this.wsObj,
        "create",
        5000,
        this.chartOption.interfaceKey,
        this.sendHeartBeat,
        this.receiveMsg,
        this.reconnectWs,
        this.wsWarning
      );
    },
    // 断网重连，需要处理的逻辑
    reconnectWs() {
      if (this.wsObj) {
        console.log("%c websocket_reconnect", "color:blue");
        this.createWs();
      }
    },
    // 以回调方式向服务端发送(对象类型的)心跳
    sendHeartBeat() {
      if (this.wsTimer != "") {
        clearTimeout(this.wsTimer);
      }

      let wsTimerTask = () => {
        console.log("发送心跳", "ping");
        let obj = { action: "keep", key: this.chartOption.interfaceKey };
        this.wsObj.send(JSON.stringify(obj));
        this.wsTimer = setTimeout(() => {
          wsTimerTask();
        }, parseInt(process.env.VUE_APP_WEBSOCKET_TIMEOUT));
        this.wsWarning();
      };

      wsTimerTask();
    },
    wsWarning() {
      //如果断开连接则显示组件警告动画并清除计数器
      if (this.wsObj.readyState == 3) {
        this.animate = "warning";
        clearTimeout(this.wsTimer);
      }
    },
    closeWs() {
      clearTimeout(this.wsTimer);
      websocketCommand(
        this.wsObj,
        "close",
        5000,
        this.chartOption.interfaceKey,
        this.sendHeartBeat,
        this.receiveMsg,
        this.reconnectWs,
        this.wsWarning
      );
      this.wsObj = null;
    }
  }
};
</script>
